package Practice;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UDPClient {
    private String ip = null;
    private int port;
    private DatagramSocket socket = null;
    public UDPClient(String ip,int port) throws SocketException {
        this.ip = ip;
        this.port = port;
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("客户端启动!");
        while (true) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("->");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(this.ip), this.port);
            socket.send(requestPacket);

            DatagramPacket responsePacket = new DatagramPacket(new byte[4086],4096);
            socket.receive(responsePacket);
            String response = new String(request.getBytes(),0,request.getBytes().length);
            System.out.println(response);
        }

    }
}
